package com.ficus.road.maintain.authority.controller;

import com.ficus.road.maintain.authority.dao.RoleDao;
import com.ficus.road.maintain.authority.dao.UserDao;
import com.ficus.road.maintain.authority.service.RoleService;
import com.ficus.road.maintain.authority.vo.DeleteRoleRelationVO;
import com.ficus.road.maintain.authority.vo.InsertRoleRelationVO;
import com.ficus.road.maintain.authority.vo.RoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiawen yang
 * @date 2021/8/25 下午7:22
 */
@RestController
@RequestMapping("/authority")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDao userDao;

    //全量查询角色
    @GetMapping("/roles")
    @PreAuthorize("@rm.check()")
    public ResponseEntity<List<RoleVO>> getAllRoles() {
        List<RoleVO> roles = roleService.queryAllRoles();
        return new ResponseEntity<>(roles, HttpStatus.OK);
    }

    //更新角色权限
    @PatchMapping("/roles/{roleId}")
    @PreAuthorize("@rm.check()")
    public ResponseEntity<String> updateUser(@PathVariable("roleId") String roleId,
                                             @RequestBody RoleVO roleVO) {
        String id = roleService.updateRoleAuthorityConfig(roleId, roleVO);
        return new ResponseEntity<>(id, HttpStatus.OK);
    }

    //取消角色关联用户
    @DeleteMapping("/relations")
    @PreAuthorize("@rm.check()")
    public ResponseEntity<String> deleteRelations(@Validated @RequestBody DeleteRoleRelationVO roleRelationVO) {
        roleService.deleteRelation(roleRelationVO.getRoleId(), roleRelationVO.getUserId());
        return new ResponseEntity<>(roleRelationVO.getRoleId(), HttpStatus.OK);
    }

    //增加角色关联用户
    @PutMapping("/relations")
    @PreAuthorize("@rm.check()")
    public ResponseEntity<String> createRelations(@Validated @RequestBody InsertRoleRelationVO roleRelationVO) {
        roleService.createRelation(roleRelationVO.getRoleId(), roleRelationVO.getUserIdList());
        return new ResponseEntity<>(roleRelationVO.getRoleId(), HttpStatus.OK);
    }
}
